import java.util.LinkedList;

class FreePartition {
    int startAddress;  // 起始地址
    int size;          // 大小
    boolean allocated; // 是否已分配

    public FreePartition(int startAddress, int size) {
        this.startAddress = startAddress;
        this.size = size;
        this.allocated = false;
    }
}

class MemoryManager {
    LinkedList<FreePartition> freePartitionList; // 空闲分区链表

    public MemoryManager() {
        freePartitionList = new LinkedList<>();
        // 假设初始内存是一个空闲分区
        freePartitionList.add(new FreePartition(0, 1024)); // 初始内存大小为1024单元
    }

    // 内存分配操作
    public void allocateMemory(int size) {
        // 实现首次适应分配算法
        for (FreePartition partition : freePartitionList) {
            if (!partition.allocated && partition.size >= size) {
                if (partition.size == size) {
                    // 如果空闲分区与请求大小相等
                    partition.allocated = true;
                } else if (partition.size - size < 1024) {
                    // 如果剩余空闲空间小于1024单元，则分配整个分区
                    partition.allocated = true;
                } else {
                    // 如果剩余空闲空间大于等于1024单元，则分割分区
                    int remainingSize = partition.size - size;
                    partition.size = size;
                    partition.allocated = true;

                    FreePartition remainingPartition = new FreePartition(partition.startAddress + size, remainingSize);
                    freePartitionList.add(freePartitionList.indexOf(partition) + 1, remainingPartition);
                }
                return;
            }
        }
        System.out.println("分配失败，找不到合适的空闲分区。");
    }

    // 内存回收操作
    public void deallocateMemory(int startAddress, int size) {
        for (FreePartition partition : freePartitionList) {
            if (partition.startAddress == startAddress) {
                partition.allocated = false;
                // 实现内存合并（合并相邻的空闲分区）
                mergeAdjacentFreePartitions();
                return;
            }
        }
        System.out.println("回收失败，找不到匹配的已分配分区。");
    }

    // 合并相邻的空闲分区
    private void mergeAdjacentFreePartitions() {
        for (int i = 0; i < freePartitionList.size() - 1; i++) {
            FreePartition currentPartition = freePartitionList.get(i);
            FreePartition nextPartition = freePartitionList.get(i + 1);

            if (!currentPartition.allocated && !nextPartition.allocated) {
                currentPartition.size += nextPartition.size;
                freePartitionList.remove(nextPartition);
                i--; // 重新检查
            }
        }
    }
}